<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>同步目录配置编辑器</title>
    <style>
      :root {
        --primary-color: #4285f4;
        --danger-color: #ea4335;
        --success-color: #34a853;
        --warning-color: #fbbc05;
        --light-gray: #f5f5f5;
        --border-color: #e0e0e0;
      }

      body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        margin: 0;
        padding: 20px;
        background-color: #f9f9f9;
        color: #333;
        line-height: 1.6;
      }

      .container {
        width: 100%;
        overflow: auto;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 25px;
        box-sizing: border-box;
      }

      h1 {
        color: var(--primary-color);
        margin-top: 0;
        padding-bottom: 15px;
        border-bottom: 1px solid var(--border-color);
      }

      .form-row {
        display: flex;
        gap: 15px;
        margin-bottom: 20px;
      }

      .form-group {
        flex: 1;
      }

      label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #555;
      }

      input[type="text"] {
        width: 95%;
        padding: 10px 12px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        box-sizing: border-box;
      }

      input[type="text"]:focus {
        border-color: var(--primary-color);
        outline: none;
        box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
      }

      .button-group {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        /* justify-content: space-between; */
      }

      button {
        padding: 10px 16px;
        border-radius: 4px;
        border: none;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s;
        font-size: 14px;
        color: white;
        box-sizing: border-box;
      }

      button.primary {
        background-color: var(--primary-color);
        color: white;
      }

      button.success {
        background-color: var(--success-color);
        color: white;
      }

      button.danger {
        background-color: var(--danger-color);
        color: white;
        padding: 5px 8px;
        font-size: 12px !important;
        box-sizing: border-box;
      }

      button:hover {
        opacity: 0.9;
        transform: translateY(-1px);
      }

      button:active {
        transform: translateY(0);
      }

      #dirTable {
        width: 100%;
        min-width: 600px;
        border-collapse: collapse;
        margin-top: 20px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        font-size: 12px;
        table-layout: fixed;
      }

      th {
        background-color: var(--light-gray);
        padding: 12px 15px;
        box-sizing: border-box;
        text-align: left;
        font-weight: 600;
        color: #555;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      td {
        padding: 12px 15px;
        box-sizing: border-box;
        border-top: 1px solid var(--border-color);
        vertical-align: middle;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .actions {
        white-space: nowrap;
      }

      .empty-state {
        text-align: center;
        padding: 40px 0;
        color: #777;
      }

      .status-bar {
        margin-top: 20px;
        padding: 10px;
        box-sizing: border-box;
        background-color: var(--light-gray);
        border-radius: 4px;
        font-size: 13px;
        color: #666;
      }

      .message-container {
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 1000;
      }

      .message {
        padding: 10px 16px;
        border-radius: 4px;
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: 500;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        opacity: 0;
        transition: opacity 0.3s, transform 0.3s;
        transform: translateY(-10px);
      }

      .message.show {
        opacity: 1;
        transform: translateY(0);
      }

      .message.success {
        background-color: #f6ffed;
        border: 1px solid #b7eb8f;
        color: #52c41a;
      }

      .message.error {
        background-color: #fff1f0;
        border: 1px solid #ffccc7;
        color: #ff4d4f;
      }

      .message.info {
        background-color: #e6f7ff;
        border: 1px solid #91d5ff;
        color: #1890ff;
      }

      .message.warning {
        background-color: #fffbe6;
        border: 1px solid #ffe58f;
        color: #faad14;
      }

      th:nth-child(3),
      td:nth-child(3) {
        width: 20%;
      }

      .w100 {
        width: 60px !important;
      }

      .w80 {
        width: 60px !important;
      }

      progress {
        width: 400px;
        height: 18px;
      }

      /* 新增定时关机样式 */
      .shutdown-group {
        display: flex;
        gap: 10px;
      }

      input[type="number"] {
        padding: 10px 12px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        font-size: 14px;
        width: 150px;
        transition: border-color 0.3s;
      }

      input[type="number"]:focus {
        border-color: var(--primary-color);
        outline: none;
        box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
      }
    </style>
    <!-- 引入 Vue.js CDN -->
    <script src="./public/vue.js"></script>
    <script src="./renderer.js" type="module">
      // const { ipcRenderer } = require('electron');
    </script>
  </head>

  <body>
    <div id="app">
      <div class="container">
        <div style="width: 100%; display: flex; justify-content: space-between">
          <h1>同步目录配置编辑器</h1>
          <h6 @click="addDev" style="cursor: pointer" class="success">
            {{isDev?'关闭':'开启'}}调试
          </h6>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="src">源目录路径</label>
            <input
              type="text"
              id="src"
              v-model="src"
              placeholder="例如: C:\Users\pc\Desktop\SFPro\Safety.Update\SAE_INTRA\Bussiness\js\pg\EmergencyManagement"
            />
          </div>

          <div class="form-group">
            <label for="dest">目标目录路径</label>
            <input
              type="text"
              id="dest"
              v-model="dest"
              placeholder="例如: \\192.168.0.110\www\SAE_INTRA\Bussiness\js\pg\EmergencyManagement"
            />
          </div>
          <div class="form-group">
            <label for="remark">备注</label>
            <input
              type="text"
              id="remark"
              v-model="remark"
              placeholder="添加备注（可选）"
            />
          </div>
        </div>

        <div class="button-group">
          <!-- 修改按钮，添加加载状态判断 -->
          <button @click="saveConfig" class="success" :disabled="isSaving">
            <!-- 根据加载状态显示不同文本 -->
            {{ isSaving ? '导出中...' : '导出配置' }}
          </button>
          <button @click="loadConfig" class="success">导入配置</button>
          <button @click="addDirectoryPair" class="primary">添加目录对</button>
          <button @click="convertImages" class="primary">转换图片格式</button>

          <button id="work" class="primary">开始同步</button>
          <!-- 新增定时关机输入组 -->
          <div class="shutdown-group">
            <input
              type="number"
              id="shutdownMinutes"
              placeholder="输入分钟数"
              min="1"
            />
            <button @click="scheduleShutdown" class="danger">
              {{this.isClose?'取消':'关机'}}( <span v-if="isCountingDown">剩余时间: {{ remainingSeconds }} 秒</span>
          <span v-else>暂未开始</span>)
            </button>
          </div>
        </div>
        <div v-if="progress!=0" style="font-size: 14px; display: flex">
          <div style="width: 70px">同步进度:</div>
          <progress style="flex: 1" :value="progress" max="100"></progress>
        </div>
        <table id="dirTable">
          <thead>
            <tr>
              <th width="auto">源目录</th>
              <th width="auto">目标目录</th>
              <th width="60px">备注</th>
              <th class="actions" width="60px">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="directories.length === 0">
              <td colspan="4" class="empty-state">暂无目录配置，请添加</td>
            </tr>
            <tr v-else v-for="(dir, index) in directories" :key="index">
              <td>{{ dir.src.replace(/\\/g, '\\\\') }}</td>
              <td>{{ dir.dest.replace(/\\/g, '\\\\') }}</td>
              <td class="w100">{{ dir.remark }}</td>
              <td class="actions w80">
                <button @click="deleteDirectoryPair(index)" class="danger">
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <div class="status-bar">
          当前配置数: <span>{{ directories.length }}</span> | 最后保存时间:
          <span>{{ lastSaveTime }}</span>
        </div>

        <div v-if="messages.length > 0" class="message-container">
          <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message', msg.type, 'show']"
            @click="removeMessage(index)"
          >
            {{ msg.content }}
          </div>
        </div>
      </div>
    </div>

    <script>
      const vm = new Vue({
        el: "#app",
        data: {
          src: "",
          dest: "",
          isSaving: false,
          isDev: false,
          remark: "",
          isClose: false,
          directories: [],
          lastSaveTime: "从未保存",
          messages: [],
          progress: 0,
          remainingSeconds: 0,
          isCountingDown: false,
          countdownInterval: null,
        },
        mounted() {
          const { ipcRenderer } = require("electron");
          const savedConfig = localStorage.getItem("syncDirectoriesConfig");
          if (savedConfig) {
            try {
              this.directories = JSON.parse(savedConfig);
            } catch (err) {
              console.error("解析本地存储配置失败:", err);
            }
          }
          const savedLastSaveTime = localStorage.getItem("lastSaveTime");
          if (savedLastSaveTime) {
            this.lastSaveTime = new Date(savedLastSaveTime).toLocaleString();
          }
          // 监听文件复制进度事件
          ipcRenderer.on("total-file-copy-progress", (event, { progress }) => {
            this.progress = progress;
          });
          
          // 监听倒计时开始事件
          ipcRenderer.on('shutdown-countdown-start', (event, { totalSeconds }) => {
            this.isCountingDown = true;
            this.remainingSeconds = totalSeconds;
          });
          
          // 监听倒计时更新事件
          ipcRenderer.on('shutdown-countdown-update', (event, { remainingSeconds }) => {
            this.remainingSeconds = remainingSeconds;
          });
          
          // 监听倒计时结束事件
          ipcRenderer.on('shutdown-countdown-end', () => {
            this.isCountingDown = false;
            this.remainingSeconds = 0;
          });
          
          // 监听倒计时取消事件
          ipcRenderer.on('shutdown-countdown-cancel', () => {
            this.isCountingDown = false;
            this.remainingSeconds = 0;
          });
        },
        watch: {
          directories: {
            handler() {
              this.autoSave();
            },
            deep: true,
          },
        },
        methods: {
          convertImages() {
            const { ipcRenderer } = require("electron");
            ipcRenderer
              .invoke("open-directory-dialog")
              .then((result) => {
                if (!result.canceled && result.filePaths.length > 0) {
                  const inputDir = result.filePaths[0];
                  ipcRenderer
                    .invoke("convert-images", inputDir)
                    .then((conversionResult) => {
                      console.log(conversionResult, "conversionResult");
                      this.showMessage(
                        `成功转换 ${conversionResult.converted} 张图片`,
                        "success"
                      );
                    })
                    .catch((err) => {
                      this.showMessage(`图片转换失败: ${err.message}`, "error");
                    });
                }
              })
              .catch((err) => {
                this.showMessage(`选择目录失败: ${err.message}`, "error");
              });
          },
          autoSave() {
            localStorage.setItem(
              "syncDirectoriesConfig",
              JSON.stringify(this.directories)
            );
            const now = new Date();
            localStorage.setItem("lastSaveTime", now.toISOString());
            this.lastSaveTime = now.toLocaleString();
          },
          showMessage(content, type, duration = 3000) {
            this.messages.push({ content, type });
            setTimeout(() => {
              this.removeMessage(0);
            }, duration);
          },
          addDev() {
            this.isDev = !this.isDev;
            const { ipcRenderer } = require("electron");
            ipcRenderer.invoke("dev", this.isDev);
          },
          addDirectoryPair() {
            const srcValue = this.src.trim();
            const destValue = this.dest.trim();
            const remarkValue = this.remark.trim();

            if (srcValue && destValue) {
              this.directories.push({
                src: srcValue,
                dest: destValue,
                remark: remarkValue,
              });
              this.src = "";
              this.dest = "";
              this.remark = "";
              this.showMessage("目录对添加成功", "success");
            } else {
              this.showMessage("请输入源目录和目标目录路径", "warning");
            }
          },
          saveConfig() {
            const { ipcRenderer } = require("electron");
            // 开始导出，设置加载状态为 true
            this.isSaving = true;
            const data = JSON.stringify(this.directories, null, 2);
            ipcRenderer
              .invoke("save-config", data)
              .then((result) => {
                if (result.success) {
                  this.showMessage(result.message, "success");
                } else {
                  this.showMessage(result.message, "error");
                }
              })
              .catch((error) => {
                this.showMessage(`导出发生错误: ${error.message}`, "error");
              })
              .finally(() => {
                // 无论成功或失败，都取消加载状态
                this.isSaving = false;
              });
          },
          loadConfig() {
            const input = document.createElement("input");
            input.type = "file";
            input.accept = ".json";

            input.onchange = (e) => {
              const file = e.target.files[0];
              const reader = new FileReader();

              reader.onload = (event) => {
                try {
                  this.directories = JSON.parse(event.target.result);
                  this.autoSave();
                  this.showMessage("导入成功", "success");
                } catch (err) {
                  this.showMessage("解析配置文件失败", "error");
                }
              };

              reader.readAsText(file);
            };

            input.click();
          },
          deleteDirectoryPair(index) {
            this.directories.splice(index, 1);
          },
          removeMessage(index) {
            this.messages.splice(index, 1);
          },
          // 新增定时关机方法
          scheduleShutdown() {
            const { ipcRenderer } = require("electron");
            const minutesInput = document.getElementById("shutdownMinutes");
            const minutes = parseInt(minutesInput.value, 10);

            if (isNaN(minutes) || minutes < 1) {
              this.showMessage("请输入有效的分钟数", "error");
              return;
            }

            const seconds = minutes * 60;
            
            // 切换关机状态
            this.isClose = !this.isClose;
            
            // 通过 IPC 发送消息到主进程
            ipcRenderer.invoke("schedule-shutdown", { t: seconds, close: !this.isClose })
              .then((result) => {
                if (result.success) {
                  this.showMessage(!this.isClose ? `已取消关机` : `已设置 ${minutes} 分钟后关机`, "success");
                } else {
                  this.showMessage(result.message, "error");
                }
              })
              .catch((err) => {
                this.showMessage(`设置关机失败: ${err.message}`, "error");
              });
          },
        },
      });
    </script>
  </body>
</html>